package com.matt.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.matt.system.domain.TSysuser;
import com.matt.tools.IpUtil;

public class LoginFilter extends HttpServlet implements Filter{

	/**
	 * 登录过滤器
	 * 2012-09-16
	 * 3:34
	 * by MATT
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response; 
		HttpSession session = req.getSession(true); 
		
		String url=req.getServletPath();  
		String contextPath=req.getContextPath();
		
		String ip1 = IpUtil.getIpAddrByRequest(req);
		String ip2 = IpUtil.getRealIp();
		
		TSysuser user = null;
		// 从session里取的用户名信息  
		//这里获取session，为了检查session里有没有保存用户信息，没有的话回转发到登陆页面
		if(!url.endsWith("index.jsp")){
			user = (TSysuser) session.getAttribute("user");
			if(user==null){
				 // 重定向到登陆页面  
				res.sendRedirect(contextPath+"/index.jsp");
				//System.out.println("用户没有登陆，不允许操作"); 
				res.setHeader("Cache-Control","no-store"); 
				res.setDateHeader("Expires",0);
				res.setHeader("Pragma","no-cache");
			}
		}
		// 已经登陆,继续此次请求 
		chain.doFilter(req,res); 
		if(ip1!=null && ip2!= null){
			System.out.println("用户已经登陆，允许操作,outNet_IP:"+ip1+",地区："+IpUtil.getAddress(ip1)+"("+IpUtil.getIpArea(ip1)+")"); 
			System.out.println("用户已经登陆，允许操作,local_IP:"+IpUtil.getAddress(ip2)); 
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}
}
